package beautiful.butterfly.distributed_task_processing_engine.task_manage.task_data_items_processor;

import beautiful.butterfly.distributed_task_processing_engine.task_manage.task_processor.TaskProcessorInfo;
import lombok.Getter;
import lombok.Setter;

import java.sql.Timestamp;
import java.util.Comparator;

public class TaskProcessorComparator implements Comparator<TaskProcessorInfo>
{
    @Setter
    @Getter
    String[] orderFields;

    public TaskProcessorComparator(String s)
    {
        if (s != null)
        {
            orderFields = s.toUpperCase().split(",");
        } else
        {
            orderFields = "task_type,register_time,heartbeat_time,ip".toUpperCase().split(",");
        }
    }

    public int compareObject(String o1, String o2)
    {
        if (o1 == null && o2 == null)
        {
            return 0;
        } else if (o1 != null)
        {
            return o1.compareTo(o2);
        } else
        {
            return -1;
        }
    }

    public int compareObject(Timestamp o1, Timestamp o2)
    {
        if (o1 == null && o2 == null)
        {
            return 0;
        } else if (o1 != null)
        {
            return o1.compareTo(o2);
        } else
        {
            return -1;
        }
    }

    public int compare(TaskProcessorInfo o1, TaskProcessorInfo o2)
    {
        int result = 0;
        for (String name : orderFields)
        {
            if (name.equals("task_type_id"))
            {
                result = compareObject(o1.getTaskId(), o2.getTaskId());
                if (result != 0)
                {
                    return result;
                }
            } else if (name.equals("register_time"))
            {
                result = compareObject(o1.getRegisterTimestamp(), o2.getRegisterTimestamp());
                if (result != 0)
                {
                    return result;
                }
            } else if (name.equals("heartbeat_time"))
            {
                result = compareObject(o1.getHeartBeatTimestamp(), o2.getHeartBeatTimestamp());
                if (result != 0)
                {
                    return result;
                }
            } else if (name.equals("ip"))
            {
                result = compareObject(o1.getIp(), o2.getIp());
                if (result != 0)
                {
                    return result;
                }
            } else if (name.equals("jvm_instance_id"))
            {
                result = compareObject(o1.getJvmInstanceId(), o2.getJvmInstanceId());
                if (result != 0)
                {
                    return result;
                }
            }
        }
        return result;
    }
}
